<template>
  <div>
    <el-container style="height: 900px; border: 1px solid #eee">
      <!-- 顶部导航栏 -->
      <el-header style="font-size: 40px; background-color: rgb(238, 241, 246)">
        <div class="header-left">
          <span>书缘校园-校园二手书交流系统</span>
        </div>
        <div class="header-right">
          <router-link to="/mySetting">
            <el-avatar src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png"></el-avatar>
          </router-link>
        </div>
      </el-header>

      <el-container>
        <!-- 侧边栏 -->
        <aside-layout></aside-layout>

        <!-- 主内容区 -->
        <el-main>
          <!-- 书籍统计卡片 -->
          <el-card class="stat-card">
            <div slot="header" class="clearfix">
              <span>书籍统计</span>
            </div>
            <el-row :gutter="20">
              <el-col :span="6">
                <div class="stat-item">
                  <span>总书籍数</span>
                  <span class="stat-value">{{ totalBooks }}</span>
                </div>
              </el-col>
              <el-col :span="6">
                <div class="stat-item">
                  <span>已归还</span>
                  <span class="stat-value">{{ returnedBooks }}</span>
                </div>
              </el-col>
              <el-col :span="6">
                <div class="stat-item">
                  <span>未归还</span>
                  <span class="stat-value">{{ unreturnedBooks }}</span>
                </div>
              </el-col>
            </el-row>
          </el-card>

          <!-- 搜索框和筛选 -->
          <el-row :gutter="20" style="margin-bottom: 20px;">
            <el-col :span="8">
              <el-input v-model="searchQuery" placeholder="请输入书名或作者" clearable @clear="fetchBooks">
                <el-button slot="append" icon="el-icon-search" @click="handleSearch"></el-button>
              </el-input>
            </el-col>
            <el-col :span="6">
              <el-select v-model="selectedCategory" placeholder="选择分类" @change="fetchBooks" style="width: 100%;">
                <el-option label="所有分类" value=""></el-option>
                <el-option label="小说" value="小说"></el-option>
                <el-option label="教材" value="教材"></el-option>
                <el-option label="其他" value="其他"></el-option>
              </el-select>
            </el-col>
            <el-col :span="6">
              <el-select v-model="sortBy" placeholder="排序方式" @change="fetchBooks" style="width: 100%;">
                <el-option label="默认排序" value=""></el-option>
                <el-option label="价格升序" value="priceAsc"></el-option>
                <el-option label="价格降序" value="priceDesc"></el-option>
                <el-option label="租入时间升序" value="rentalTimeAsc"></el-option>
                <el-option label="租入时间降序" value="rentalTimeDesc"></el-option>
                <el-option label="归还时间升序" value="returnTimeAsc"></el-option>
                <el-option label="归还时间降序" value="returnTimeDesc"></el-option>
              </el-select>
            </el-col>
            <el-col :span="4">
              <el-button type="primary" @click="showAdvancedFilter = true">高级筛选</el-button>
              <el-button @click="resetFilters">清除筛选</el-button>
            </el-col>
          </el-row>

          <!-- 书籍列表 -->
          <el-table :data="filteredBooks"
            style="width: 100%; border-radius: 8px; box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);"
            :row-style="{ cursor: 'pointer' }"
            :header-cell-style="{ background: '#f5f7fa', color: '#333', fontWeight: 'bold' }"
            :cell-style="{ padding: '12px 8px' }">
            <el-table-column prop="name" label="书名" width="200"></el-table-column>
            <el-table-column prop="author" label="作者" width="150"></el-table-column>
            <el-table-column prop="price" label="价格" width="120"></el-table-column>
            <el-table-column prop="category" label="分类" width="120"></el-table-column>
            <el-table-column prop="intro" label="简介" width="300"></el-table-column>
            <el-table-column prop="rental_time" label="租入时间" width="180"></el-table-column>
            <el-table-column prop="return_time" label="归还时间" width="180"></el-table-column>
            <el-table-column prop="status" label="状态" width="120"></el-table-column>
            <el-table-column label="操作" width="200">
              <template slot-scope="scope">
                <el-button type="text" @click="handleRenew(scope.row)">续租</el-button>
                <el-button type="text" @click="handleReturn(scope.row)">归还</el-button>
                <el-button type="text" @click="handleMarkAsReturned(scope.row)">标记已归还</el-button>
                <el-button type="text" @click="handleMarkAsUnreturned(scope.row)">标记未归还</el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
            :current-page="currentPage" :page-sizes="[10, 20, 30, 40]" :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper" :total="totalBooks"
            style="margin-top: 20px;"></el-pagination>

          <!-- 高级筛选弹窗 -->
          <el-dialog title="高级筛选" :visible.sync="showAdvancedFilter" width="50%">
            <el-form :model="advancedFilter">
              <el-form-item label="价格范围">
                <el-input-number v-model="advancedFilter.minPrice" placeholder="最低价格"></el-input-number>
                <span style="margin: 0 10px;">-</span>
                <el-input-number v-model="advancedFilter.maxPrice" placeholder="最高价格"></el-input-number>
              </el-form-item>
              <el-form-item label="租入时间范围">
                <el-date-picker v-model="advancedFilter.minRentalTime" type="date" placeholder="开始时间"></el-date-picker>
                <span style="margin: 0 10px;">-</span>
                <el-date-picker v-model="advancedFilter.maxRentalTime" type="date" placeholder="结束时间"></el-date-picker>
              </el-form-item>
              <el-form-item label="归还时间范围">
                <el-date-picker v-model="advancedFilter.minReturnTime" type="date" placeholder="开始时间"></el-date-picker>
                <span style="margin: 0 10px;">-</span>
                <el-date-picker v-model="advancedFilter.maxReturnTime" type="date" placeholder="结束时间"></el-date-picker>
              </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
              <el-button @click="showAdvancedFilter = false">取消</el-button>
              <el-button type="primary" @click="applyAdvancedFilter">应用</el-button>
            </span>
          </el-dialog>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script>
import AsideLayout from '../../layout/AsideLayout.vue';
import axios from 'axios'; // 引入 axios

export default {
  components: { AsideLayout },
  data() {
    return {
      searchQuery: '', // 搜索框内容
      selectedCategory: '', // 选择的分类
      sortBy: '', // 排序方式
      tableData: [], // 书籍列表数据
      currentPage: 1, // 当前页码
      pageSize: 10, // 每页显示的条数
      totalBooks: 0, // 总书籍数量
      showAdvancedFilter: false, // 高级筛选弹窗的显示状态
      advancedFilter: {
        minPrice: null,
        maxPrice: null,
        minRentalTime: null,
        maxRentalTime: null,
        minReturnTime: null,
        maxReturnTime: null
      }
    };
  },
  computed: {
    // 根据搜索、分类和排序过滤书籍
    filteredBooks() {
      let books = this.tableData;

      // 搜索过滤
      if (this.searchQuery) {
        books = books.filter(book => book.name.includes(this.searchQuery) || book.author.includes(this.searchQuery));
      }

      // 分类过滤
      if (this.selectedCategory) {
        books = books.filter(book => book.category === this.selectedCategory);
      }

      // 价格范围过滤
      if (this.advancedFilter.minPrice) {
        books = books.filter(book => book.price >= this.advancedFilter.minPrice);
      }
      if (this.advancedFilter.maxPrice) {
        books = books.filter(book => book.price <= this.advancedFilter.maxPrice);
      }

      // 租入时间范围过滤
      if (this.advancedFilter.minRentalTime) {
        books = books.filter(book => new Date(book.rental_time) >= new Date(this.advancedFilter.minRentalTime));
      }
      if (this.advancedFilter.maxRentalTime) {
        books = books.filter(book => new Date(book.rental_time) <= new Date(this.advancedFilter.maxRentalTime));
      }

      // 归还时间范围过滤
      if (this.advancedFilter.minReturnTime) {
        books = books.filter(book => new Date(book.return_time) >= new Date(this.advancedFilter.minReturnTime));
      }
      if (this.advancedFilter.maxReturnTime) {
        books = books.filter(book => new Date(book.return_time) <= new Date(this.advancedFilter.maxReturnTime));
      }

      // 排序
      if (this.sortBy === 'priceAsc') {
        books = books.sort((a, b) => a.price - b.price);
      } else if (this.sortBy === 'priceDesc') {
        books = books.sort((a, b) => b.price - a.price);
      } else if (this.sortBy === 'rentalTimeAsc') {
        books = books.sort((a, b) => new Date(a.rental_time) - new Date(b.rental_time));
      } else if (this.sortBy === 'rentalTimeDesc') {
        books = books.sort((a, b) => new Date(b.rental_time) - new Date(a.rental_time));
      } else if (this.sortBy === 'returnTimeAsc') {
        books = books.sort((a, b) => new Date(a.return_time) - new Date(b.return_time));
      } else if (this.sortBy === 'returnTimeDesc') {
        books = books.sort((a, b) => new Date(b.return_time) - new Date(a.return_time));
      }

      return books;
    },
    // 已归还书籍数量
    returnedBooks() {
      return this.tableData.filter(book => book.status === '已归还').length;
    },
    // 未归还书籍数量
    unreturnedBooks() {
      return this.tableData.filter(book => book.status === '未归还').length;
    }
  },
  methods: {
    // 获取书籍列表
    async fetchBooks() {
      try {
        const response = await axios.get('http://localhost:3000/api/borrowed-books', {
          params: {
            page: this.currentPage,
            size: this.pageSize
          }
        });
        this.tableData = response.data.borrowedBooks;
        this.totalBooks = response.data.total;
      } catch (error) {
        this.$message.error('获取数据失败，请重试');
      }
    },
    // 搜索书籍
    handleSearch() {
      this.fetchBooks();
    },
    // 分页大小改变
    handleSizeChange(size) {
      this.pageSize = size;
      this.fetchBooks();
    },
    // 当前页改变
    handleCurrentChange(page) {
      this.currentPage = page;
      this.fetchBooks();
    },
    // 续租书籍
    handleRenew(row) {
      this.$confirm('确定要续租这本书吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const response = await axios.post(`http://localhost:3000/api/renew-book/${row.id}`, {
            rental_time: new Date().toISOString().split('T')[0] // 格式化为 YYYY-MM-DD
          });
          if (response.data.success) {
            this.$message.success('续租成功');
            row.rental_time = response.data.rental_time;
          } else {
            this.$message.error('续租失败，请重试');
          }
        } catch (error) {
          this.$message.error('续租失败，请重试');
        }
      }).catch(() => {
        this.$message.info('已取消续租');
      });
    },
    // 归还书籍
    handleReturn(row) {
      this.$confirm('确定要归还这本书吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const response = await axios.post(`http://localhost:3000/api/return-book/${row.id}`, {
            return_time: new Date().toISOString().split('T')[0] // 格式化为 YYYY-MM-DD
          });
          if (response.data.success) {
            this.$message.success('归还成功');
            row.return_time = response.data.return_time;
            row.status = '已归还';
          } else {
            this.$message.error('归还失败，请重试');
          }
        } catch (error) {
          this.$message.error('归还失败，请重试');
        }
      }).catch(() => {
        this.$message.info('已取消归还');
      });
    },
    // 标记为已归还
    handleMarkAsReturned(row) {
      this.$confirm('确定要将这本书标记为已归还吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const response = await axios.post(`http://localhost:3000/api/mark-returned/${row.id}`, {
            status: '已归还'
          });
          if (response.data.success) {
            this.$message.success('标记已归还成功');
            row.status = '已归还';
          } else {
            this.$message.error('标记已归还失败，请重试');
          }
        } catch (error) {
          this.$message.error('标记已归还失败，请重试');
        }
      }).catch(() => {
        this.$message.info('已取消标记');
      });
    },
    // 标记为未归还
    handleMarkAsUnreturned(row) {
      this.$confirm('确定要将这本书标记为未归还吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const response = await axios.post(`http://localhost:3000/api/mark-unreturned/${row.id}`, {
            status: '未归还'
          });
          if (response.data.success) {
            this.$message.success('标记未归还成功');
            row.status = '未归还';
          } else {
            this.$message.error('标记未归还失败，请重试');
          }
        } catch (error) {
          this.$message.error('标记未归还失败，请重试');
        }
      }).catch(() => {
        this.$message.info('已取消标记');
      });
    },
    // 重置筛选条件
    resetFilters() {
      this.searchQuery = '';
      this.selectedCategory = '';
      this.sortBy = '';
      this.advancedFilter = {
        minPrice: null,
        maxPrice: null,
        minRentalTime: null,
        maxRentalTime: null,
        minReturnTime: null,
        maxReturnTime: null
      };
      this.fetchBooks();
    },
    // 应用高级筛选
    applyAdvancedFilter() {
      this.showAdvancedFilter = false;
      this.fetchBooks();
    }
  },
  mounted() {
    this.fetchBooks(); // 页面加载时获取数据
  }
};
</script>

<style scoped>
.el-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  font-weight: bold;
}

.header-right {
  display: flex;
  align-items: center;
}

.header-right a {
  margin-right: 20px;
  color: #333;
  text-decoration: none;
}

.el-table {
  margin-top: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.el-table__header th {
  background-color: #f5f7fa;
  color: #333;
  font-weight: bold;
}

.el-table__body tr:hover {
  background-color: #f0f9eb;
}

.el-pagination {
  margin-top: 20px;
}

.el-dialog__body {
  padding: 20px;
}

.stat-card {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.stat-item {
  text-align: center;
  font-size: 16px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #409EFF;
}
</style>